package org.iteam.core.service.mysql.impl.sys;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.iteam.core.Constant;
import org.iteam.core.model.sys.SysAuth;
import org.iteam.core.model.sys.SysUser;
import org.iteam.core.service.sys.SysUserService;
import org.iteam.core.utils.DateUtil;
import org.iteam.core.utils.SqlBuilder;
import org.iteam.core.view.sys.SysPermissionView;

public class SysUserServiceImpl extends SysUserService {

	public boolean create(SysUser obj) throws SQLException {
		SqlBuilder sb = SqlBuilder.createInsert(SysUser.TABLE_NAME);
		sb.addField("account", obj.getAccount());
		sb.addField("password", obj.getPassword());
		sb.addField("name", obj.getName());
		sb.addField("alias", obj.getAlias());
		sb.addField("status", obj.getStatus());
		sb.addField("create_time", DateUtil.currentTime());
		return super.update(sb.getSql().toUpperCase(), sb.getParams());
	}

	public List<SysUser> queryByPage(long page, long rows) throws SQLException {
		return super.query(
				"select * from "
						+ SysUser.TABLE_NAME
						+ " order by account ,create_time desc limit ? , ?  "
								.toUpperCase(), (page - 1) * rows, rows);
	}

	@Override
	public List<SysPermissionView> getPermissionsAll() {
		String sql = "SELECT A.AUTH_ROLE AS PERMISSION_ROLE, C.MODE AS AUTH_MODE, D.* FROM SYS_AUTH A INNER JOIN SYS_ROLE B ON A.AUTH_ROLE = B. CODE INNER JOIN SYS_PERMISSION C ON C.PERMISSION_ROLE = A.AUTH_ROLE INNER JOIN SYS_FUNCTION D ON D. CODE = C.PERMISSION_FUNCTION WHERE B. STATUS = ? AND D. STATUS = ? ";
		try {
			return super.query(SysPermissionView.class, sql,
					Constant.Status.ENABLE.ecode, Constant.Status.ENABLE.ecode);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return new ArrayList<SysPermissionView>();
	}

	public boolean updateUserRole(String account, String role,
			boolean _permission) throws SQLException {
		SqlBuilder sb = null;
		if (_permission) {
			sb = SqlBuilder.createInsert(SysAuth.TABLE_NAME);
			sb.addField("auth_role", role);
			sb.addField("auth_user", account);
			sb.addField("pri", 1);
			sb.addField("beg_time", DateUtil.currentTime());
			sb.addField("end_time", DateUtil.currentTime());
		} else {
			sb = SqlBuilder.createDelete(SysAuth.TABLE_NAME);
			sb.addWhere("auth_role", role);
			sb.addWhere("auth_user", account);
		}

		return super.update(sb.getSql().toUpperCase(), sb.getParams());
	}
}
